package com.jeeplus.test.jlnu.student.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeeplus.test.jlnu.student.domain.entity.BkbsssStudentObtain;
import com.jeeplus.test.jlnu.student.domain.entity.StudentInfoApprove;
import com.jeeplus.test.jlnu.student.domain.vo.BkbsssStudentObtainReqVo;
import com.jeeplus.test.jlnu.student.domain.vo.BsssStudentGraduateVo;
import com.jeeplus.test.jlnu.student.dto.VerifyResponse;
import com.jeeplus.test.jlnu.student.dto.command.UpdateStudentObtainBatchCommand;
import com.jeeplus.test.jlnu.student.mapper.BkbsssStudentObtainMapper;
import com.jeeplus.test.jlnu.student.mapper.StudentInfoApproveMapper;
import com.jeeplus.test.jlnu.student.service.BkbsssStudentObtainService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class BkbsssStudentObtainServiceImpl extends ServiceImpl<BkbsssStudentObtainMapper, BkbsssStudentObtain> implements BkbsssStudentObtainService {
    @Autowired
    private  BkbsssStudentObtainMapper bkbsssStudentObtainMapper;

    @Autowired
    StudentInfoApproveMapper studentInfoApproveMapper;

    @Override
    public BkbsssStudentObtain getBkbsssStudentObtain(String studentId,String flag) {
        LambdaQueryChainWrapper<BkbsssStudentObtain> wrapper = new LambdaQueryChainWrapper<>(bkbsssStudentObtainMapper);
        wrapper.eq(BkbsssStudentObtain::getStudentId, studentId)
                .eq(BkbsssStudentObtain::getFlag,flag);
        return wrapper.one();
    }

    @Override
    public Boolean bkbsssStudentObtainUpdate(BsssStudentGraduateVo bkbsssStudentObtain) {
        LambdaUpdateChainWrapper<BkbsssStudentObtain> wrapper = new LambdaUpdateChainWrapper<>(bkbsssStudentObtainMapper);
        if (ObjectUtil.isNotEmpty(bkbsssStudentObtain.getEmploymentUnitName())){
            wrapper.set(BkbsssStudentObtain::getEmploymentUnitName,bkbsssStudentObtain.getEmploymentUnitName());
        }
        if (ObjectUtil.isNotEmpty(bkbsssStudentObtain.getEmploymentUnitAddress())){
            wrapper.set(BkbsssStudentObtain::getEmploymentUnitAddress,bkbsssStudentObtain.getEmploymentUnitAddress());
        }
        if (ObjectUtil.isNotEmpty(bkbsssStudentObtain.getFileTransferNumber())){
            wrapper.set(BkbsssStudentObtain::getFileTransferNumber,bkbsssStudentObtain.getFileTransferNumber());
        }
        if (ObjectUtil.isNotEmpty(bkbsssStudentObtain.getFileTransferType())){
            wrapper.set(BkbsssStudentObtain::getFileTransferType,bkbsssStudentObtain.getFileTransferType());
        }
        if (ObjectUtil.isNotEmpty(bkbsssStudentObtain.getTransferUnitPostalCode())){
            wrapper.set(BkbsssStudentObtain::getTransferUnitPostalCode,bkbsssStudentObtain.getTransferUnitPostalCode());
        }
        if (ObjectUtil.isNotEmpty(bkbsssStudentObtain.getFileReceivingUnitName())){
            wrapper.set(BkbsssStudentObtain::getFileReceivingUnitName,bkbsssStudentObtain.getFileReceivingUnitName());
        }
        if (ObjectUtil.isNotEmpty(bkbsssStudentObtain.getFileReceivingUnitAddress())){
            wrapper.set(BkbsssStudentObtain::getFileReceivingUnitAddress,bkbsssStudentObtain.getFileReceivingUnitAddress());
        }
        if (ObjectUtil.isNotEmpty(bkbsssStudentObtain.getTransferUnitLocationCode())){
            wrapper.set(BkbsssStudentObtain::getTransferUnitLocationCode,bkbsssStudentObtain.getTransferUnitLocationCode());
        }
        if (ObjectUtil.isNotEmpty(bkbsssStudentObtain.getFileReceiver())){
            wrapper.set(BkbsssStudentObtain::getFileReceiver,bkbsssStudentObtain.getFileReceiver());
        }
        if (ObjectUtil.isNotEmpty(bkbsssStudentObtain.getReceiverPhone())){
            wrapper.set(BkbsssStudentObtain::getReceiverPhone,bkbsssStudentObtain.getReceiverPhone());
        }

        LambdaQueryChainWrapper<StudentInfoApprove> queryWrapper =
                new LambdaQueryChainWrapper<>(studentInfoApproveMapper);

        // 查询是否存在记录
        Optional<StudentInfoApprove> info = queryWrapper
                .eq(StudentInfoApprove::getStudentId, bkbsssStudentObtain.getStudentId())
                .eq(StudentInfoApprove::getOutsideType, "4")
                .eq(StudentInfoApprove::getFlag, bkbsssStudentObtain.getFlag())
                .oneOpt();


        // 生成 VerifyResponse 的 JSON 数据
        String data = generateVerifyResponseJson(bkbsssStudentObtain);

        // 根据查询结果执行更新或插入
        if (info.isPresent()) {
            // 更新操作
            StudentInfoApprove studentInfoApprove = new StudentInfoApprove();
            studentInfoApprove.setContent(data);
            studentInfoApprove.setStudentId(bkbsssStudentObtain.getStudentId());
            studentInfoApprove.setOutsideType("4");
            studentInfoApprove.setApprovalStatus(0);
            studentInfoApprove.setName(bkbsssStudentObtain.getName());
            studentInfoApprove.setIdCardNumber(bkbsssStudentObtain.getIdCardNumber());
            studentInfoApprove.setFlag(bkbsssStudentObtain.getFlag());
            studentInfoApproveMapper.updateStudentInfoApprove(studentInfoApprove);
        } else {
            // 插入操作
            StudentInfoApprove studentInfoApprove = createNewStudentInfoApprove(data,bkbsssStudentObtain);
            studentInfoApprove.setOutsideType("4");
            studentInfoApprove.setApprovalStatus(0);
            studentInfoApproveMapper.insertStudentInfoApprove(studentInfoApprove);
        }


        //根据id修改
        wrapper.eq(BkbsssStudentObtain::getId, bkbsssStudentObtain.getId());
        return wrapper.update();
    }


    // 生成 VerifyResponse 的 JSON 数据
    private String generateVerifyResponseJson(BsssStudentGraduateVo bsssStudentGraduate) {
        try {
            // 日期格式化
            VerifyResponse verifyResponse = new VerifyResponse();
            if(bsssStudentGraduate.getBirthDate() != null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String birthDateStr = sdf.format(bsssStudentGraduate.getBirthDate());
                verifyResponse.setBirthDate(birthDateStr);
            }
            BeanUtils.copyProperties(bsssStudentGraduate, verifyResponse);
            verifyResponse.setFileReceivingUnitName(bsssStudentGraduate.getFileReceivingUnitName());
            verifyResponse.setFileReceivingUnitAddress(bsssStudentGraduate.getFileReceivingUnitAddress());
            verifyResponse.setFileReceiver(bsssStudentGraduate.getFileReceiver());
            verifyResponse.setReceiverPhone(bsssStudentGraduate.getReceiverPhone());
            // JSON 序列化
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(verifyResponse);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON 序列化失败", e);
        }
    }
    // 创建新记录对象
    private StudentInfoApprove createNewStudentInfoApprove(String data, BsssStudentGraduateVo bsssStudentGraduate) {
        StudentInfoApprove studentInfoApprove = new StudentInfoApprove();
        studentInfoApprove.setStudentId(bsssStudentGraduate.getStudentId());
        studentInfoApprove.setContent(data);
        studentInfoApprove.setOfficeId(bsssStudentGraduate.getOfficeId());
        studentInfoApprove.setFlag(bsssStudentGraduate.getFlag());
        studentInfoApprove.setApprovalStatus(0);
        return studentInfoApprove;
    }

    @Override
    public void updateBatch(UpdateStudentObtainBatchCommand updateStudentObtainBatchCommand) {
        BkbsssStudentObtain studentObtain = updateStudentObtainBatchCommand.getStudentObtain();
        for (Integer studentObtainId : updateStudentObtainBatchCommand.getStudentObtainIds()) {
            studentObtain.setId(studentObtainId);
            bkbsssStudentObtainMapper.updateById(studentObtain);
        }
    }
    private void copyNonNullProperties(Object source,Object target){
        if(source == null || target == null){
            return;
        }
        Field[] sourceFields = source.getClass().getDeclaredFields();
        for(Field sourceField : sourceFields){
            if("ids".equals(sourceField.getName())){
                continue;
            }
            try{
                sourceField.setAccessible(true);
                Object value = sourceField.get(source);
                if (value != null){
                    Field targetField = ReflectionUtils.findField(target.getClass(),sourceField.getName());
                    if(targetField != null){
                        targetField.setAccessible(true);
                        targetField.set(target,value);
                    }
                }
            }catch (IllegalArgumentException | IllegalAccessException e){
                log.warn("复制属性时发生异常: {}");
            }
        }
    }
    @Override
    public boolean batchUpdate(BkbsssStudentObtainReqVo bkbsssStudentObtainReqVo){
        if(bkbsssStudentObtainReqVo.getIds() == null || bkbsssStudentObtainReqVo.getIds().trim().isEmpty()){
            throw new IllegalArgumentException("ids不能为空");
        }
        List<Long> idList = Arrays.stream(bkbsssStudentObtainReqVo.getIds().split(",")).map(idStr ->{
            try{
                return Long.parseLong(idStr.trim());
            } catch (NumberFormatException e){
                throw new IllegalArgumentException("ids格式不正确: " + idStr);
            }
        }).collect(Collectors.toList());
        UpdateWrapper<BkbsssStudentObtain> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id",idList);
        BkbsssStudentObtain entity = new BkbsssStudentObtain();
        copyNonNullProperties(bkbsssStudentObtainReqVo, entity);
        return update(entity,updateWrapper);
    }
    @Override
    public boolean saveOrUpdateBkbsssStudentObtain(BkbsssStudentObtain bkbsssStudentObtain) {
        return super.saveOrUpdate(bkbsssStudentObtain);
    }
    @Override
    public Page<BkbsssStudentObtain> selectAllBkbsssStudentObtainVOs(BkbsssStudentObtainReqVo bkbsssStudentObtainReqVo, Page<BkbsssStudentObtain> page){

        Page<BkbsssStudentObtain> qualificationInfoPage = bkbsssStudentObtainMapper.selectAllBkbsssStudentObtainVOs(bkbsssStudentObtainReqVo,page);
        return qualificationInfoPage;

    }
    @Override
    public ResponseEntity<byte[]> DataDowload(List<String> ids) {
        // 1. 校验输入参数非空
        if (ids == null || ids.isEmpty()) {
            throw new IllegalArgumentException("ID列表不能为空");
        }

        // 2. 将String类型的ids转换为Integer类型
        List<Integer> integerIds;
        try {
            integerIds = ids.stream()
                    .map(idStr -> {
                        String trimmedId = idStr != null ? idStr.trim() : "";
                        if (trimmedId.isEmpty()) {
                            throw new IllegalArgumentException("ID不能为空字符串");
                        }
                        return Integer.parseInt(trimmedId);
                    })
                    .collect(Collectors.toList());
        } catch (NumberFormatException e) {
            throw new RuntimeException("ID格式错误，必须是整数：" + e.getMessage(), e);
        }

        // 3. 使用转换后的Integer IDs查询数据
        List<BkbsssStudentObtain> studentObtains = bkbsssStudentObtainMapper.selectBatchIds(integerIds);

        if (studentObtains == null || studentObtains.isEmpty()) {
            return ResponseEntity.noContent().build();
        }

        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            // 4. 关键修复：完整复制所有字段到VO类
            List<BkbsssStudentObtainReqVo> exportData = studentObtains.stream()
                    .map(obtain -> {
                        BkbsssStudentObtainReqVo vo = new BkbsssStudentObtainReqVo();
                        // 手动复制所有需要导出的字段（确保与VO类字段匹配）
                        vo.setId(obtain.getId());
                        vo.setEmploymentUnitName(obtain.getEmploymentUnitName());
                        vo.setEmploymentUnitAddress(obtain.getEmploymentUnitAddress());
                        vo.setFileTransferNumber(obtain.getFileTransferNumber());
                        vo.setFileTransferType(obtain.getFileTransferType());
                        vo.setTransferUnitPostalCode(obtain.getTransferUnitPostalCode());
                        vo.setFileReceivingUnitName(obtain.getFileReceivingUnitName());
                        vo.setFileReceivingUnitAddress(obtain.getFileReceivingUnitAddress());
                        vo.setTransferUnitLocationCode(obtain.getTransferUnitLocationCode());
                        vo.setFileReceiver(obtain.getFileReceiver());
                        vo.setReceiverPhone(obtain.getReceiverPhone());
                        vo.setFlag(obtain.getFlag());
                        vo.setStudentId(obtain.getStudentId());
                        vo.setOfficeId(obtain.getOfficeId());
                        vo.setApprovalStatus(obtain.getApprovalStatus());
                        vo.setRejectReason(obtain.getRejectReason());
                        vo.setModifyApprovalStatus(obtain.getModifyApprovalStatus());
                        vo.setRejectionReasonItem(obtain.getRejectionReasonItem());
                        vo.setModificationOpinions(obtain.getModificationOpinions());
                        vo.setModificationTime(obtain.getModificationTime());
                        vo.setViewStatus(obtain.getViewStatus());
                        return vo;
                    })
                    .collect(Collectors.toList());

            // 5. 导出Excel（使用VO列表）
            EasyExcel.write(outputStream, BkbsssStudentObtainReqVo.class)
                    .sheet("转递信息")
                    .doWrite(exportData);

            // 6. 构建响应头
            HttpHeaders headers = new HttpHeaders();
            String fileName = "转递信息_" + System.currentTimeMillis() + ".xlsx";
            // 1. 正确设置Content-Type（xlsx格式专用）
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            // 2. 规范文件名编码（处理特殊字符）
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
            // 3. 正确设置Content-Disposition（兼容各种浏览器）
            headers.setContentDispositionFormData("attachment", encodedFileName);


            return ResponseEntity.ok()
                    .headers(headers)
                    .body(outputStream.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败：" + e.getMessage(), e);
        }
    }

    @Override
    public int batchUpdateMailing(BkbsssStudentObtainReqVo bkbsssStudentObtainReqVo) {
        return bkbsssStudentObtainMapper.batchUpdateMailing(bkbsssStudentObtainReqVo.getAdmissionInfoList(),bkbsssStudentObtainReqVo.getTransferState());
    }

    @Override
    public BkbsssStudentObtainReqVo selectBkbsssStudentObtainById(Long id){
        return baseMapper.selectBkbsssStudentObtainById(id);
    }
}
